import java.util.Calendar;
import java.util.Vector;

public class AutoHome {

	private static String className = "AutoHome: ";
	private static ScheduleThread scheduleThread;
	private static EventScheduler eventScheduler;
	private static Vector<ScheduleEvent> scheduleEvents = new Vector<ScheduleEvent>();
	private static Vector<ScheduledEvent> scheduledEvents = new Vector<ScheduledEvent>();
	private static Vector<Device> devices = new Vector<Device>();
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("auto-home");

		// GeneralSettings.saveSettings();

		init();

		int latestRefreshDay = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
		
		while (true) {
			try {
								
					if(latestRefreshDay != Calendar.getInstance().get(Calendar.DAY_OF_WEEK))
					{
						latestRefreshDay = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
						refresh(); //JOAX: Change to event based refresh
					}
					
					Thread.sleep(60000); //Sleep 1 min
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
	}

	private static void refresh() {
		scheduleThread.setScheduledEvents(eventScheduler.rebuildScheduledEvents());
	}

	private static void init() {
		GeneralSettings.loadSettings();
		ScheduleSettings.loadSettings(scheduleEvents);

		TellstickInterface.init(GeneralSettings.tdToolFilePath, GeneralSettings.tellstickRepetitions);
		devices = TellstickDeviceFileInterface.loadDevicesFromFile(GeneralSettings.tellstickDeviceFilePath);

		// ScheduleEvent testScheduleEvent = new ScheduleEvent();
		// Vector<ScheduleEvent> scheduleEvents = new Vector<ScheduleEvent>();
		// scheduleEvents.add(testScheduleEvent);

		// Vector<Device> devices = new Vector<Device>();
		// testScheduleEvent.switchOn = false;
		// testScheduleEvent.weekdays = Macros.setWeekday(Calendar.FRIDAY,
		// testScheduleEvent.weekdays);
		// testScheduleEvent.startHour = 0;
		// testScheduleEvent.startMinute = 16;
		// testScheduleEvent.devices = Macros.setDevice((byte)1,
		// testScheduleEvent.devices);
		// testScheduleEvent.eventType = EventType.TIME_EVENT;
		//
		eventScheduler = new EventScheduler(scheduleEvents);

		scheduleThread = new ScheduleThread(eventScheduler.rebuildScheduledEvents(), devices);
		scheduleThread.start();

		// tmp
		// DeviceSettings.saveSettings(devices);
		// ScheduleSettings.saveSettings(scheduleEvents);
	}

}